import lx from './app-jssdk.umd.min'
import { Toast } from 'vant';
import { Dialog } from 'vant';
import config from './config'
import http from './httpRequest'
import httploading from "./httploadingRequest"
import cache from './cache'
import util from './validate'

export default {

  /**
   * 从蓝信获取免登录授权码
   */
  getAuthorCode(appId){
    let authCode = lx.biz.getAuthCode({
      appId: appId
    })
    console.log(authCode)
    return authCode
  },

  /**
   * 根据免登授权码获取登录人员信息
   */
  async getUserInfo(appId, type) {
    console.log("lx-appId--->" + appId)
    console.log("lx-appType--->" + type)

    let authCode = await this.getAuthorCode(appId)
    console.log("lx-authCode--->" + JSON.stringify(authCode))
    if (util.isEmpty(authCode)) {
      Toast("获取蓝信免登授权码失败")
      return;
    }
    console.log("lx-url--->"+config.baseUrl + config.lxUserUrl)
    await http({
      url: config.baseUrl + config.lxUserUrl,
      method: 'get',
      params: {
        'authCode': authCode.authCode,
        'type': util.isEmpty(type) ? 'search' : type,
      }
    }).then(({data}) => {
      console.log('lx-userInfo-->' + JSON.stringify(data));
      if (data.code == 200) {
        let userInfo = data.userInfo
        if(userInfo != null) {
          cache.set('lxUserInfo', userInfo)
        } else {
          Toast('获取蓝信用户信息失败')
        }
        // let expire = data.expire
        // let userToken = userInfo.userToken
        // cache.setByExpire('userInfo', userInfo, expire)
        // cache.setByExpire('userToken', userToken, expire)
      } else {
        Toast(data.msg)
      }
    })
  },



  /**
   * 调wps
   * @param fileName 文件名
   * @param fileUrl  文件url
   * @param saveUrl  修改后保存的url
   * @param openMode 打开模式，支持"ReadOnly"、"Normal"、"ReadMode"、"EditMode",ReadMode仅支持android，如果ios传该值默认EditMode
   */
  wps(fileName, fileUrl, saveUrl, openMode) {
    console.log('进入wps方法:'+cache.get('appType'))
    // 先签名再调
    let type = cache.get('appType')
    http({
      url: config.baseUrl + config.signatureUrl,
      method: 'get',
      params: {'type':type}
    }).then(({data}) => {
      console.log('--------签名：')
      console.log(data)
      if(data.code == 200) {
        lx.config({
          appId: cache.get("appId"), // 必填，应用的唯一标识
          timestamp: data.timestamp, // 必填，生成签名的10位时间戳，int型，单位：秒
          nonceStr: data.noncestr, // 必填，生成签名的随机串
          signature: data.signature // 必填，签名
        });
        // 调用wps
        lx.internal.biz.wpsSignOff({
          fileName: fileName,
          fileUrl: fileUrl,
          saveUrl: saveUrl,
          openMode: openMode
        })
      } else {
        Toast(data.msg)
      }
    })
  },
  /**
   * 打开ofd文件
   * @param fileUrl
   * mode: 进入的模式[viewer、editor]
   * permissions: 允许的权限[read、review、approve]。
   * 1、当模式为 viewer 时
   *  (1)当权限为[read]时，只有查看功能
   *  (2)当权限为[read、review]时，显示查阅按钮功能
   *  (3)当权限为[read、approve]时，显示批阅按钮功能
   * 2、当模式为 editer 时
   *  (1)当权限为[read、approve]时，显示批阅功能
   */
  ofd(fileUrl){
    console.log("开始打开ofd："+fileUrl)
    lx.utils.downloadFile({
      url: fileUrl,
      success: function (res) {
        console.log("downloadFile res：")
        console.log(res)
        lx.utils.signFile({
          platform: 'OFD',
          url: res.localId,
          mode: 'viewer',
          permissions: ['read']
        })
      },
      fail: function (err) {
        console.log(err)
      },
    });


  },
  /**
   *  打开word文件：1）先获文件的打开权限，2）调用蓝信的打开word功能
   * @param item
   * @param proInstId
   * @returns {Promise<void>}
   */
  async openFile(item,proInstId){
    console.log('文件详情：'+JSON.stringify(item)+',proInstId:'+proInstId)
    //如果是word 文件，则需要根据权限打开
    if(item.attachType == 'doc' || item.attachType == 'docx' || item.attachType == 'wps'){
      //获取文件的权限
      let openMode = await this.getOpenStateAndNewDoc(item.attachId)
      if(openMode  == this.openMode.readOnly){
        Dialog.confirm({
          message: '您正在编辑此文件，再次打开的是只读文件，是否打开文件？',
        }).then(() => {
          this.openFileDetail(item.attachName,item.attachType,
              config.basePCUrl+'/caac/platform/UploadChunkController/download?attachId='+item.attachId+'&systemKey='+cache.get('userInfo').systemKey+'&systemFlag='+cache.get('userInfo').systemFlag,
              config.basePCUrl + '/caac/oa/app/documentUpload?proInstId=' + proInstId+'&systemKey='+cache.get('userInfo').systemKey+'&systemFlag='+cache.get('userInfo').systemFlag,
              openMode)
        }).catch(() => {
          // on cancel
        });
      }else if(openMode  == this.openMode.editMode){
        this.openFileDetail(item.attachName, item.attachType,
            config.basePCUrl + '/caac/platform/UploadChunkController/download?attachId=' + item.attachId+'&systemKey='+cache.get('userInfo').systemKey+'&systemFlag='+cache.get('userInfo').systemFlag,
            config.basePCUrl + '/caac/oa/app/documentUpload?proInstId=' + proInstId +'&systemKey='+cache.get('userInfo').systemKey+'&systemFlag='+cache.get('userInfo').systemFlag,
            openMode)
      }else if(openMode == 'withdraw'){
        Toast('文件已被撤回！')
      }
    }else{
      this.openFileDetail(item.attachName,item.attachType,
          config.basePCUrl+'/caac/platform/UploadChunkController/download?attachId='+item.attachId+'&systemKey='+cache.get('userInfo').systemKey+'&systemFlag='+cache.get('userInfo').systemFlag,
          config.basePCUrl + '/caac/oa/app/documentUpload?proInstId=' + proInstId+'&systemKey='+cache.get('userInfo').systemKey+'&systemFlag='+cache.get('userInfo').systemFlag)
    }
  },

  /**
   * 获取文件的操作权限,只包括wps，doc，docx
   * {"code":200,"data":{"openState":"edit","newFileId":"5a51c2e3b9e94607aae2bebaf990db6c"},"message":null}
   *   edit-可编辑，
   *   withdraw-文件已撤回，
   *   返回其他值：有人正在编辑此文件，只能只读打开
   * @returns {Promise<string>}
   */
  async getOpenStateAndNewDoc(attachId){
    let openMode = this.openMode.readMode   //默认以只读方式打开
    await httploading({
      url: httploading.adornUrl('/caac/wfm/MhjDocumentCommonController/getOpenStateAndNewDoc'),
      method: 'get',
      params: httploading.adornParams({
        'systemKey': cache.get('userInfo').systemKey,//固定值
        'systemFlag': cache.get('userInfo').systemFlag,//固定值
        'attachId': attachId,
        'actInstId ': '',//目前PC系统传了空字符串
      })
    }).then(({data}) => {
      if(data.code==200){
        console.log("获取权限："+JSON.stringify(data))
        if (data.data.openState == 'edit'){
          openMode = this.openMode.editMode
        }else if(data.data.openState == 'readonly'){
          openMode = this.openMode.readOnly

        }else if(data.data.openState == 'withdraw'){
          openMode = data.data.openState
        }
      }
    })
    return openMode
  },

  /**
   * 打开文件详情
   * @param attachName  文件名
   * @param attachType  文件后缀(不带点)
   * @param openUrl     打开url
   * saveUrl 和openMode 主要适用与wps和doc文件
   * @param saveUrl     保存url
   * @param openMode    打开模式，支持"ReadOnly"、"Normal"、"ReadMode"、"EditMode",不传的话默认取ReadMode
   */
  openFileDetail(attachName, attachType, openUrl, saveUrl='', openMode=this.openMode.readMode) {
    console.log('打开wps参数：fileName-->'+attachName+',文件后缀-->'+attachType+',openUrl-->'+openUrl+',saveUrl-->'+saveUrl)
    // this.fileLog(attachName, openUrl, openMode);
    attachType = attachType.toLowerCase()//后缀统一改为小写
    if (attachType == 'pdf') {
      uni.navigateTo({
        url: '/pages/pdfPreview?pdfUrl='+encodeURIComponent(openUrl)
      });
    } else if (attachType == 'ofd') {
      if(this.isAndroid()){
        this.ofd(openUrl)
      }else{
        Toast.fail('ios 暂不支持ofd文件预览功能,敬请期待!')
      }
    } else if (attachType == 'doc' || attachType == 'docx' || attachType == 'txt'
      || attachType == 'xls' || attachType == 'xlsx'
      || attachType == 'ppt' || attachType == 'pptx' || attachType == 'wps') {
      saveUrl = config.basePCUrl + '/caac/oa/app/documentUpload' //默认保存地址
      this.wps(attachName, openUrl, saveUrl, openMode)

    } else if (attachType == 'png' || attachType == 'jpg' || attachType == 'jpeg' || attachType == 'svg'){
      // 预览图片
      uni.previewImage({
        urls: [openUrl],
      });
    }else{
      Toast('暂不支持' + attachType + '文件在线打开')
    }
  },

  openMode: {
    readOnly: 'ReadOnly',
    normal: 'Normal',
    readMode: 'ReadMode',
    editMode: 'EditMode'
  },
  //判断安卓还是iOS
  isAndroid() {
    let platform = uni.getSystemInfoSync().platform
    if (platform == 'ios') {
      return false;
    } else if (platform == 'android') {
      return true;
    }
  },

  /**
   * 发送消息
   * @param type app类型，例如‘oa’
   * @param userIds 用户Id
   * @param title 公文标题
   * @param gwType 公文类型，例如局内便函、收文等
   * @param link 链接，例如‘/pages/caac/jnbh/index?proInstId=xxx’
   */
  sendMessage(type, userIds, title, gwType, link) {
    console.log('开始发送通知--->');
    if (!config.sendMsgStatus) {
      return ;
    }
    let lxUserInfo = cache.get('lxUserInfo')
    // let deptName = lxUserInfo.loginName.split('@')[0]
    // if (deptName == 'mhjcs') {
    //   deptName = 'CAAC';
    // }
    // 用户Id转登录名
    // httploading({
    //   url: httploading.adornUrl('/caac/oa/app/getUserCodeByUserId'),
    //   method: 'get',
    //   params: httploading.adornParams({
    //     'systemKey': cache.get('userInfo').systemKey,//固定值
    //     'systemFlag': cache.get('userInfo').systemFlag,//固定值
    //     'userId': userIds
    //   })
    // }).then(({data}) => {
    //   if (data.code == 200) {
    //     let userNames = data.data.map(item => { return deptName + '@' + item.userCode; });

    let userNames = ['mhjcs@wj-li','mhjcs@lipian']
        http({
          url: http.adornUrl('/caac-admin/lx/api/sendUserMessage'),
          method: 'post',
          data: http.adornData({
            'type': type,
            'userNames': userNames.join(','),
            'title': title,
            'gwType': gwType,
            'link': link,
          })
        }).then(({data}) => {
          if (data.code == 200) {
            Toast('发送成功！');
          } else {
            Toast(data.msg)
          }
        });
    //   } else {
    //     Toast(data.message);
    //   }
    // });
  },

  /**
   * 保存用户操作文件日志
   * @param fileName
   * @param fileUrl
   * @param fileSize
   * @param openMode
   */
  fileLog(fileName, fileUrl, fileSize, openMode) {
    http({
      url: http.adornUrl('/caac-admin/api/fileLog/insert'),
      method: 'get',
      params: http.adornParams({
        'username': cache.get('userInfo').systemKey,
        'deptName': cache.get('userInfo').deptName,
        'operation': openMode == 'EditMode' ? '签批' : '读取',
        'fileName': fileName,
        'fileUrl': fileUrl,
        'fileSize': fileSize,
      })
    }).then(({data}) => {
      console.log("filelog-insert--->" + JSON.stringify(data));
    });
  },
};
